package cn.net.mugui.net.udp;

import com.mugui.base.base.Component;
import com.mugui.base.client.net.auto.AutoManager;
import com.mugui.base.client.net.base.Manager;
import org.apache.commons.lang3.StringUtils;

@AutoManager
@Component
public class UdpServerManager extends Manager<String, UdpServer> {

    /**
     * 得到一个新的UdpServer
     *
     * @param key
     * @param host
     * @param port
     * @return
     * @author 木鬼
     */
    public UdpServer get(String key, String host, int port) {
        UdpServer udpServer = super.get(key);
        if (udpServer != null) {
            if (!host.equals(udpServer.getTo_host())) {
                udpServer.setTo_host(host);
            }
            if (port != udpServer.getTo_port()) {
                udpServer.setTo_port(port);
            }
            return udpServer;
        }
        if (StringUtils.isBlank(host) || port < 1) {
            new RuntimeException("key=" + host + "不是一个主机地址");
        }
        udpServer = new UdpServer(host, port);
        add(key, udpServer);
        return udpServer;
    }

    @Override
    public UdpServer del(String key) {
        UdpServer udpServer = super.del(key);
        if (udpServer != null)
            udpServer.close();
        return udpServer;
    }

}
